<template>
  <!-- 登录注册页面 -->
  <div class="loginbox" v-if="!user.isLogin">
    <el-switch
      v-model="user.isRegister"
      size="large"
      active-text="注册"
      inactive-text="登录"
      @change="Change"
    />
    <!-- 登录 -->
    <el-form :model="user" v-if="!user.isRegister">
      <el-form-item label="账号" label-width="70px">
        <el-input v-model="user.username" />
      </el-form-item>
      <el-form-item label="密码" label-width="70px">
        <el-input v-model="user.password" show-password/>
      </el-form-item>
      <div class="btnbox">
        <el-button @click="ForgetPassword">忘记密码</el-button>
        <el-button type="primary" @click="Login">登录</el-button>
      </div>
    </el-form>
    <!-- 注册 -->
    <el-form :model="user" v-else>
      <el-form-item label="账号" label-width="70px">
        <el-input v-model="user.username" />
      </el-form-item>
      <el-form-item label="密码" label-width="70px">
        <el-input v-model="user.password" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" label-width="70px">
        <el-input v-model="user.confirmPassword" show-password />
      </el-form-item>
      <el-form-item label="绑定" label-width="70px">
        <el-input v-model="user.bindnumber" />
      </el-form-item>
      <div class="btnbox">
        <el-button type="primary" @click="Register">注册</el-button>
      </div>
    </el-form>
  </div>
  <!-- 用户信息 -->
  <el-card class="box-card" v-if="user.isLogin">
    <template #header>
      <div class="card-header">
        <div style="display: flex; align-items: center;">
          <el-image class="imgbox" :src="userinfo.imgurl ? userinfo.imgurl : require('@/assets/logo.png')" :fit="fit" :prediv-src-list="srcList" :initial-index="0" @click="chooseImg(userinfo.imgurl)" :prediv-teleported="true" :hide-on-click-modal="true"/>
          <div style="margin-left: 15px;">{{ userinfo.name }}</div>
        </div>
        <el-button @click="Out" type="danger">退出登录</el-button>
      </div>
    </template>
    <el-tabs v-model="activeName">
      <el-tab-pane label="记录列表" name="list">
        <div class="contentbox">
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="openHistoryDrawer">历史记录</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="openTestpaperDrawer">试卷记录</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="openWrongDrawer">错题列表</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="openCollectDrawer">收藏列表</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="设置用户信息" name="uinfo">
        <div class="contentbox">
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="openAD">更换头像</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="FixName">修改昵称</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="FixBind">修改绑定</el-button>
          <el-button style="width: 100%; text-align: center; height: 50px;" text @click="isSPWDshow = true">修改密码</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
  <!-- 找回密码弹窗 -->
  <el-dialog v-model="user.isShow" title="新设密码" @close="closeUPD">
    <el-form :model="user">
      <el-form-item label="新密码" label-width="70px">
        <el-input v-model="user.pw" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" label-width="70px">
        <el-input v-model="user.cpw" show-password/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="user.isShow = false">取消</el-button>
        <el-button type="primary" @click="SetPassword">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改头像弹窗 -->
  <el-dialog v-model="isAvatarShow" title="修改头像" @close="closeAD" width="300px">
    <el-form>
      <el-form-item label="头像">
          <el-upload
            action="#"
            list-type="picture-card"
            :show-file-list="false"
            :limit="1"
            :before-upload="beforeUpload"
            >
            <el-avatar :src="avatarImgurl !== '' ? avatarImgurl : require('@/assets/logo.png')" :size="100" :fit="fit"/>
          </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isAvatarShow = false">取消</el-button>
        <el-button type="primary" @click="FixAvatar">提交</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改密码弹窗 -->
  <el-dialog v-model="isSPWDshow" title="新设密码" @close="closeSPWD">
    <el-form :model="pwform">
      <el-form-item label="旧密码" label-width="70px">
        <el-input v-model="pwform.oldpassword" show-password/>
      </el-form-item>
      <el-form-item label="新密码" label-width="70px">
        <el-input v-model="pwform.newpassword" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" label-width="70px">
        <el-input v-model="pwform.confirmPassword" show-password/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isSPWDshow = false">取消</el-button>
        <el-button type="primary" @click="FixPassword">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 记录列表弹窗 -->
  <!-- 历史记录 -->
  <el-drawer v-model="histroyData.drawer" title="历史记录" direction="ltr">
    <el-scrollbar height="100%">
      <div v-for="item in histroyData.historylist" :key="item" class="listitem">
        <div @click="NavToHistory(item.time, '做题')" class="item">
          <text>{{getNowDate(item.time)}}</text><text>{{item.subject}}{{item.type}}</text>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
  <!-- 试卷做题记录 -->
  <el-drawer v-model="testpaperData.drawer" title="试卷做题记录" direction="ltr">
    <el-scrollbar height="100%">
      <div v-for="item in testpaperData.testpaperlist" :key="item" class="listitem">
        <div @click="NavToHistory(item.time, '试卷')" class="item">
          <text>{{getNowDate(item.time)}}</text><text>{{ item.testpaper }}</text>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
  <!-- 错题记录 -->
  <el-drawer v-model="wrongData.drawer" title="错题列表" direction="ltr">
    <el-scrollbar height="100%">
      <div v-for="item in wrongData.wronglist" :key="item" class="listitem">
        <div @click="NavToWrong(item.subject)" class="item">
          <text>{{item.subject}}</text><text>{{item.questionIds.length}}</text>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
  <!-- 收藏列表 -->
  <el-drawer v-model="collectData.drawer" title="收藏列表" direction="rtl">
    <el-scrollbar height="100%">
      <div v-for="(item, index) in collectData.collectlist" :key="item" class="listitem">
        <div @click="NavToCollect(item)" class="item">
          <text>{{item.foldername}}</text><text>{{item.questionIds.length}}</text>
        </div>
        <el-button @click="clickSlipe(item, index)">删除</el-button>
      </div>
    </el-scrollbar>
  </el-drawer>
</template>

<script setup>
  import { login, getuserinfo, register, forgetpassword, setpassword, setimgurl, setname, setbind } from '@/api/user.js'
  import { gethistorylist, getwronglist, getcollectlist, delcollectfolder } from '@/api/question.js'
  import { ref, onBeforeMount } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  import { storeToRefs } from 'pinia'
  import { useStore } from '../../store'
  import { useRouter } from 'vue-router'
  const store = useStore()
  const router = useRouter()

  const user = ref({
    isLogin: false,
    username: '',
    password: '',
    confirmPassword: '',
    bindnumber: '',
    isRegister: false,
    isShow: false,
    pw: '',
    cpw: ''
  })

  onBeforeMount(() => {
    GetUserInfo()
  })
  // 登录
  const Login = () => {
    if (user.value.username.split(' ').join('') === '' || user.value.password.split(' ').join('') === '') {
      ElMessage.error('输入内容不能为空')
      return
    }
    login({
      username: user.value.username,
      password: user.value.password
    }).then((res) => {
      Success(res.userInfo.username)
      store.userinfo = res.userInfo
    })
  }
  // 登录或注册成功
  const Success = (username) => {
    localStorage.setItem('token', username)
    user.value.username = ''
    user.value.password = ''
    user.value.confirmPassword = ''
    user.value.isLogin = true
    user.value.bindnumber = ''
  }
  // 退出登录
  const Out = () => {
    user.value.isLogin = false
    user.value.name = ''
    user.value.imgurl = ''
    store.userinfo = {
      username: '',
      password: '',
      imgurl: '',
      bind: '',
      name: ''
    }
    localStorage.removeItem('token')
  }
  // 获取用户信息
  const GetUserInfo = () => {
    if (localStorage.getItem('token') && userinfo.username !== '') {
      user.value.isLogin = true
      getuserinfo({
        username: localStorage.getItem('token')
      }).then((res) => {
        // console.log(res)
        store.userinfo = res.userInfo
      })
    } else if (localStorage.getItem('token')) {
      user.value.isLogin = true
    }
  }
  // 切换登录/注册
  const Change = (value) => {
    user.value.username = ''
    user.value.password = ''
    user.value.confirmPassword = ''
    user.value.bindnumber = ''
  }
  // 注册
  const Register = () => {
    if (user.value.password.split(' ').join('') === '' || user.value.password !== user.value.confirmPassword) {
      ElMessage.error('密码不为空或确认密码不一致')
      return
    }
    if (user.value.bindnumber.split(' ').join('') === '' || user.value.username.split(' ').join('') === '') {
      ElMessage.error('账号或绑定为空')
      return
    }
    register({
      username: user.value.username,
      password: user.value.password,
      bind: user.value.bindnumber
    }).then(res => {
      const userInfo = {
        username: user.value.username,
        password: '',
        name: user.value.username,
        imgurl: '',
        bind: user.value.bindnumber
      }
      Success(userInfo.username)
      store.userinfo = userInfo
    })
  }
  // 忘记密码
  const ForgetPassword = () => {
    ElMessageBox.prompt('请输入绑定的手机号/QQ', '修改绑定', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    .then(({ value }) => {
      console.log(value)
      forgetpassword({
        username: user.value.username,
        bind: value
      }).then(res => {
        user.value.isShow = true
      })
    })
    .catch(() => {})
  }
  // 关闭找回密码弹窗
  const closeUPD = () => {
    user.value.pw = ''
    user.value.cpw = ''
  }
  // 新设密码
  const SetPassword = () => {
    if (user.value.pw.split(' ').join('') === '' || user.value.pw !== user.value.cpw) {
      ElMessage.error('密码为空或确认密码不一致')
      return
    }
    setpassword({
      username: user.value.username,
      oldpassword: null,
      newpassword: user.value.pw
    }).then(res => {
      ElMessage.success('修改成功')
      user.value.isShow = false
    })
  }

  // 用户信息
  const activeName = ref('list')
  const userinfo = storeToRefs(store).userinfo
  // 预览图片
  const srcList = ref([])
  const chooseImg = (imgurl) => {
    const url = imgurl || require('@/assets/logo.png')
    srcList.value[0] = url
  }

  // 修改头像
  const isAvatarShow = ref(false)
  const avatarImgurl = ref('')
  const openAD = () => {
    avatarImgurl.value = userinfo.value.imgurl
    isAvatarShow.value = true
  }
  const closeAD = () => {
    avatarImgurl.value = ''
  }
  // 图片转base64
  const beforeUpload = (file) => {
    const reader = new FileReader()
    // 文件装载后将其显示在图片预览里
    reader.onload = function (e) {
      // 将bade64位图片保存至数组里供上面图片显示
      avatarImgurl.value = e.target.result
    }
    // 将文件以DataURL形式读入页面
    reader.readAsDataURL(file)
    return false
  }
  // 修改头像
  const FixAvatar = () => {
    setimgurl({
      username: userinfo.value.username,
      imgurl: avatarImgurl.value
    }).then(res => {
      ElMessage.success('修改头像成功')
      store.userinfo.imgurl = avatarImgurl.value
      isAvatarShow.value = false
      avatarImgurl.value = ''
    })
  }
  // 修改昵称
  const FixName = () => {
    ElMessageBox.prompt(`旧昵称：${userinfo.value.name}`, '修改昵称', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    .then(({ value }) => {
      // console.log(value)
      setname({
        username: userinfo.value.username,
        name: value
      }).then(res => {
        ElMessage.success('修改昵称成功')
        store.userinfo.name = value
      })
    })
    .catch(() => {})
  }
  // 修改绑定
  const FixBind = () => {
    ElMessageBox.prompt(`旧绑定：${userinfo.value.bind}`, '修改绑定', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    .then(({ value }) => {
      // console.log(value)
      setbind({
        username: userinfo.value.username,
        bind: value
      }).then(res => {
        ElMessage.success('修改昵称成功')
        store.userinfo.bind = value
      })
    })
    .catch(() => {})
  }
  // 修改密码
  const isSPWDshow = ref(false)
  const pwform = ref({
    oldpassword: '',
    newpassword: '',
    confirmPassword: ''
  })
  const closeSPWD = () => {
    pwform.value = {
      oldpassword: '',
      newpassword: '',
      confirmPassword: ''
    }
  }
  // 修改密码
  const FixPassword = () => {
    if (pwform.value.oldpassword.split(' ').join('') === '' || pwform.value.newpassword.split(' ').join('') === '' || pwform.value.newpassword !== pwform.value.confirmPassword) {
      ElMessage.error('密码为空或确认密码不一致')
      return
    }
    setpassword({
      username: userinfo.value.username,
      ...pwform.value
    }).then(res => {
      ElMessage.success('修改成功')
      isSPWDshow.value = false
    })
  }

  // 获取时间
  const getNowDate = (time) => {
    const date = new Date(time)
    const sign2 = ':'
    const year = date.getFullYear() // 年
    let month = date.getMonth() + 1 // 月
    let day = date.getDate() // 日
    let hour = date.getHours() // 时
    let minutes = date.getMinutes() // 分
    let seconds = date.getSeconds() // 秒
    // let weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    // let week = weekArr[date.getDay()];
    // 给一位数的数据前面加 “0”
    if (month >= 1 && month <= 9) {
    month = '0' + month
    }
    if (day >= 0 && day <= 9) {
    day = '0' + day
    }
    if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
    }
    if (minutes >= 0 && minutes <= 9) {
    minutes = '0' + minutes
    }
    if (seconds >= 0 && seconds <= 9) {
    seconds = '0' + seconds
    }
    return year + '-' + month + '-' + day + ' ' + hour + sign2 + minutes + sign2 + seconds
  }
  // 历史记录
  const histroyData = ref({
    drawer: false,
    historylist: []
  })
  const openHistoryDrawer = () => {
    gethistorylist({
      username: localStorage.getItem('token'),
      type: '历史记录'
    }).then(res => {
      // that.$store.dispatch('sethistorylist', res.historylist.reverse())
      histroyData.value.historylist = res.historylist.reverse()
      histroyData.value.drawer = true
    })
  }
  const NavToHistory = (time, type) => {
    // url: `/pages/grade/grade?time=${time}&type=${type}`
    router.push({
      name: 'grade',
      query: {
        time,
        type
      }
    })
  }
  // 试卷做题记录
  const testpaperData = ref({
    drawer: false,
    testpaperlist: []
  })
  const openTestpaperDrawer = () => {
    gethistorylist({
      username: localStorage.getItem('token'),
      type: '试卷记录'
    }).then(res => {
      // that.$store.dispatch('sethistorylist', res.historylist.reverse())
      testpaperData.value.testpaperlist = res.historylist.reverse()
      testpaperData.value.drawer = true
    })
  }
  // 错题记录
  const wrongData = ref({
    drawer: false,
    wronglist: []
  })
  const openWrongDrawer = () => {
      getwronglist({
        username: localStorage.getItem('token')
      }).then(res => {
        wrongData.value.wronglist = res.wronglist
        wrongData.value.drawer = true
      })
  }
  const NavToWrong = (subject) => {
    router.push({
      name: 'analysis',
      query: {
        isAll: true,
        n: 0,
        wrongsubject: subject
      }
    })
  }
  // 收藏列表
  const collectData = ref({
    drawer: false,
    collectlist: []
  })
  const openCollectDrawer = () => {
      getcollectlist({
        username: localStorage.getItem('token')
      }).then(res => {
        collectData.value.collectlist = res.collectlist
        collectData.value.drawer = true
      })
  }
  // 删除收藏夹
  const clickSlipe = (item, index) => {
    ElMessageBox.confirm(
    `删除《${item.foldername}》收藏夹？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      delcollectfolder({
        username: localStorage.getItem('token'),
        foldername: item.foldername
      }).then(r => {
        collectData.value.collectlist.splice(index, 1)
        ElMessage.success('删除完成')
      })
    })
  }
  // 跳转收藏页面
  const NavToCollect = (item) => {
    // url: `/pages/collect/collect?foldername=${item.foldername}`,
    router.push({
      name: 'collect',
      query: {
        foldername: item.foldername
      }
    })
  }
</script>

<style>

</style>

<style lang="less" scoped>
.loginbox {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid rgba(0,0,0,.2);
  border-radius: 10px;
  padding: 30px 50px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  .btnbox {
    display: flex;
    justify-content: end;
  }
}
.box-card {
  width: 480px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .imgbox {
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
  }
  .contentbox {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
.listitem {
  display: flex;
  .item {
    flex: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    height: 40px;
    background-color: #F8F8F8;
    margin: 1vh;
    font-size: 16px;
    border: 1px solid rgba(0,0,0,.2);
    border-radius: 10px;

    &:active {
      background-color: #dedede;
    }
  }

  button {
    flex: 1;
    height: 40px;
    margin: 1vh 0;
    height: 40px;
    background-color: rgba(256, 0, 0, .7);
    color: #fff;
    border: none;
  }
}
</style>
